import Router from 'koa-router'
import axios from './utils/axios'
import Cart from '../dbs/models/cart'
import md5 from 'crypto-js/md5'

let router = new Router({
  prefix: '/cart'
})

//---------------------------    保存购物车订单     --------------------------
router.post('/create', async ctx => {
  if (!ctx.isAuthenticated())
    return (ctx.body = { code: -1, msg: 'please login' })
  let time = Date()
  let cartNo = md5(Math.random() * 1000 + time).toString() //cartNo 用MD5生成carNo序列号
  let {
    params: { id, detail }
  } = ctx.request.body //从ctx.request.body 拿到请求数据
  let cart = new Cart({
    id,
    cartNo,
    time,
    user: ctx.session.passport.user, //从session中获取用户
    detail
  })
  let result = await cart.save() //保存到mongo数据库中
  if (!result) return (ctx.body = { code: -1, msg: 'fail' })
  ctx.body = { code: 0, msg: '', id: cartNo }
})

router.post('/getCart', async ctx => {
  let { id } = ctx.request.body
  // console.log(id)
  try {
    let result = await Cart.findOne({
      cartNo: id
    })
    ctx.body = {
      code: 0,
      data: result ? result.detail[0] : {}
    }
  } catch (e) {
    ctx.body = {
      code: -1,
      data: {}
    }
  }
})

export default router
